package com.feizhoutuobang.shapeline.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.feizhoutuobang.shapeline.bo.Config;
import com.feizhoutuobang.shapeline.service.ConfigService;

public class ConfigServiceImpl extends HibernateDaoSupport implements ConfigService {
	
	private static Map<String, String> values = new HashMap<String, String>();
	private static final String HQL = "from Config where key=:key";
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public String getStringValue(String key) {
		return getValue(key);
	}

	@Override
	public int getIntegerValue(String key) {
		String value = getValue(key);
		return Integer.parseInt(value);
	}

	@Override
	public boolean getBooleanValue(String key) {
		String value = getValue(key);
		return Boolean.parseBoolean(value);
	}

	@Override
	public Date getDateValue(String key) {
		String value = getValue(key);
		try {
			return dateFormat.parse(value);
		} catch (ParseException e) {
			return null;
		}
	}
	
	private String getValue(String key) {
		if (values.containsKey(key)) {
			return values.get(key);
		}
		
		Query query = getSession().createQuery(HQL).setString("key", key);
		Object o = query.uniqueResult();
		String value = o == null ? null : ((Config)o).getValue();
		
		values.put(key, value);
		return value;
	}
}
